<template>
	<div>
		<el-input v-model="tag" :placeholder="placeholder" maxlength="30" show-word-limit :style="{ width: width }">
			<template #append>
				<el-button @click="addTag()">新增</el-button>
			</template>
		</el-input>
		<div>
			<el-tag v-for="(item, index) in getTags" :key="index" style="margin-right:7px" closable @close="delTag(index)">{{ item }}</el-tag>
		</div>
	</div>
</template>

<script lang="ts">
import { defineComponent, toRefs, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'

export default defineComponent({
	name: 'addTags',
	props: {
		tags: {
			type: String,
			default: ''
		},
		placeholder: {
			type: String,
			default: '添加关键字，最多五个'
		},
		width: {
			type: String,
			default: '70%'
		}
	},
	setup(props, { emit }) {
		const state = reactive({
			tag: '',
			myTags: props.tags.length > 0 ? props.tags.split(',') : []
		})

		const getTags = computed(() => {
			return props.tags.length > 0 ? props.tags.split(',') : []
		})

		const addTag = () => {
			if (state.tag.length === 0) return
			if (state.myTags.length === 5) {
				ElMessage.warning('最多添加五个关键字!')
				return
			}
			// 把这个值添加进去
			state.myTags.push(state.tag)
			// 然后重置这个值
			state.tag = ''
			emit('update:tags', state.myTags.toString())
		}

		const delTag = (index: Number) => {
			state.myTags.splice(index, 1)
			emit('update:tags', state.myTags.toString())
		}

		return {
			getTags,
			addTag,
			delTag,
			...toRefs(state)
		}
	}
})
</script>

<style scoped lang="scss">
.span {
	color: #8d8d91;
	font-size: 14px;
	float: left;
	padding: 0 15px;
	margin: 15px 0;
	&:hover {
		color: var(--color-primary);
		cursor: pointer;
	}
}
.selected {
	color: var(--color-primary);
}
</style>
